package edu.gatech.cs2340.sharks.fms;

/**
 * AddItemActivity.java
 * @author Steven Mitchell
 * 
 * Creates an item in the database based on the input that the user gives
 * If successful, returns to the home page.
 */

import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import edu.gatech.cs2340.sharks.fms.data.*;
import java.util.List;

public class AddItemActivity extends Activity
{	
	/**
	 * The lost or found status of the item being added. Defaults to "lost"
	 */
	private Item.Status itemStatus = Item.Status.LOST;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_add_item);
	}
	
	/**
	 * Sets lost to true or false based on which radiobutton the user has selected
	 * 
	 * @param view The button that is checked.
	 */
	public void setLostOrFound(View view)
	{
		boolean checked = ((RadioButton) view).isChecked();
		switch(view.getId())
		{
			case R.id.editLost:
			    if (checked) itemStatus = Item.Status.LOST;
			    break;
			case R.id.editFound:
			    if (checked) itemStatus = Item.Status.FOUND;
			    break;
		}
	}
	
	/**
	 * Queries the database for the list of possible tags and
	 * concatenates them into a string. Afterward, it adds the
	 * string to a dialog that is displayed to the user.
	 * 
	 * @param view The button that runs the method when clicked.
	 */
	public void displayTags(View view)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		String tagString = "";
		Packet<List<Tag>> tagList = DBMgr.allTags();

		for (Tag t : tagList.value)
		{
			if ("".equals(tagString)) tagString += t.name;
			else tagString += ", " + t.name;
		}
		
		builder.setMessage("Here are the tags you may use: \n" + tagString);
		builder.setPositiveButton("Close", new DialogInterface.OnClickListener()
		{	
			public void onClick(DialogInterface dialog, int id) { }
		});
		AlertDialog dialog = builder.create();
		dialog.show();
	}
	
	/**
	 * Obtains all user inputs, creates an item object, and stores it in the database.
	 * If successful, the activity finishes and you retuurn to the hoem screen.
	 * Else, an error is displayed.
	 * 
	 * @param view The submit button
	 */
	public void createItem(View view)
	{
		//gets the item name
		final EditText nameField = (EditText) findViewById(R.id.editItemName);
		String itemName = nameField.getText().toString();
		
		//gets the date
		final EditText yearField = (EditText) findViewById(R.id.year);
		String year = yearField.getText().toString();
		
		final EditText monthField = (EditText) findViewById(R.id.month);
		String month = monthField.getText().toString();
		
		final EditText dayField = (EditText) findViewById(R.id.day);
		String day = dayField.getText().toString();
		
		//combines the year, month, and day
		String date = year + "-" + month + "-" + day;
		
		//gets location
		final EditText locationField = (EditText) findViewById(R.id.editLocationLost);
		String locationLost = locationField.getText().toString();
		
		//gets item description
		final EditText descField = (EditText) findViewById(R.id.editItemDescription);
		String description = descField.getText().toString();
		
		//gets the reward
		final EditText rewardField = (EditText) findViewById(R.id.editReward);
		String rewardText = rewardField.getText().toString();
		int reward;
		try { reward = Integer.parseInt(rewardText); }
		catch (NumberFormatException e) { reward = 0; }
		
		//obtains the list of tags
		final EditText tagField = (EditText) findViewById(R.id.editTags);
		String tagString = tagField.getText().toString();
		
		//splits the list of tags and re-stores only the valid ones
		ArrayList<Tag> tags = new ArrayList<Tag>();
		if (tagString != null && ! "".equals(tagString))
		{
			String[] tagNames = tagString.split(",");
			Packet<List<Tag>> tagList = DBMgr.allTags();
			for (int i = 0; i < tagNames.length; i++) for (Tag t : tagList.value) if (t.name.equals(tagNames[i]))
			{
				tags.add(t);
				break;
			}
		}
		
		//assigns the valid tags to the item
		Item newItem = new Item(0, itemName, date, locationLost, description, reward, itemStatus);
		newItem.tags = tags;
		
		final TextView statusField = (TextView) findViewById(R.id.statusText);
		
		//adds the item if the date is the correct length
		Status success;
		if (date.length() == 10) success = DBMgr.createItem(DBMgr.user, newItem);
		else success = null;
		
		//finishes the activity if the item was added successfully. Otherwise, and displays error message
		if (success != null && success.code() == Status.Code.OK)
		{
			Intent nextIntent = new Intent(this, HomeActivity.class);
			startActivity(nextIntent);
			finish();
		}
		else if (date.length() != 10) statusField.setText("Please enter a valid date!" + date);
		else if (success != null) statusField.setText(success.toString());
		else statusField.setText("The query to the server returned null.");
	}

	/**
	 * Stops the activity and returns user to the home screen
	 * 
	 * @param view The button that runs this method
	 */
	public void cancel(View view)
	{
		finish();
	}
}
